import { ElMessage } from "element-plus";
import { reactive, ref } from "vue";

export function useCommonQuery(options = {}) {
  // 表格数据
  const tableData = ref([]);

  // 表格加载时的 Loading
  const loading = ref(false);

  // 弹窗参数
  const dialogParams = reactive({
    title: "",
    visible: false,
  });

  // 查询参数
  const queryParams = ref({
    ...options.newParams,
  });

  // 分页参数
  const pagingParams = reactive({
    page: 1,
    limit: 10,
    total: 0,
  });

  // 请求查询
  async function handleQuery() {
    const { queryApi } = options;
    try {
      loading.value = true;
      const { data = {} } = await queryApi({
        page: pagingParams.page,
        limit: pagingParams.limit,
        ...queryParams.value,
      });
      tableData.value = data.list;
      pagingParams.total = data.total;
      loading.value = false;
    } catch {
      loading.value = true;
      ElMessage({ type: "error", message: "未知错误" });
    }
  }

  // 提交数据
  async function handleConfirm(data) {
    try {
      if (data.id) {
        handleUpdate(data);
      } else {
        handleCreate(data);
      }
    } catch {
      ElMessage({ type: "error", message: "未知错误" });
    }
  }

  // 创建数据
  async function handleCreate(data) {
    const { createApi } = options;
    try {
      const { message } = await createApi(data);
      ElMessage({ type: "success", message });
      handleQuery();
      dialogParams.visible = false;
    } catch {
      ElMessage({ type: "error", message: "未知错误" });
    }
  }

  // 更新数据
  async function handleUpdate(data) {
    const { updateApi } = options;
    try {
      const { message } = await updateApi(data);
      ElMessage({ type: "success", message });
      handleQuery();
      dialogParams.visible = false;
    } catch {
      ElMessage({ type: "error", message: "未知错误" });
    }
  }

  // 删除数据
  async function handleDelete(id) {
    const { deleteApi } = options;
    try {
      const { message } = await deleteApi(id);
      ElMessage({ type: "success", message });
      handleQuery();
    } catch {
      ElMessage({ type: "error", message: "未知错误" });
    }
  }

  function handleReset() {
    queryParams.value = { ...options.newParams };
    handleQuery();
  }

  return {
    tableData,
    loading,
    dialogParams,
    queryParams,
    pagingParams,
    handleQuery,
    handleConfirm,
    handleDelete,
    handleReset,
  };
}
